package com.itheima.controller;


import com.itheima.common.R;
import com.itheima.entity.dto.category.CategoryDto;
import com.itheima.entity.dto.category.CategoryUpdateDto;
import com.itheima.entity.vo.category.CategoryAllPageVo;
import com.itheima.entity.vo.category.CategoryAllVo;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author huangzelnag
 * @create 2022-05-04
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    /**
     * 添加分类
     * @param categoryDto
     * @return
     */
    @PostMapping()
    public R addCategory(@RequestBody CategoryDto categoryDto){
        Boolean aBoolean = categoryService.addCategory(categoryDto);

        if(aBoolean){
            return R.success("添加成功");
        }else {
            String msg ="'分类名'已存在";
            return R.error(msg);
        }

    }

    /**
     * 更新分类
     * @param categoryUpdateDto
     * @return
     */
    @PutMapping()
    public R updateCategory(@RequestBody CategoryUpdateDto categoryUpdateDto){

        Boolean aBoolean = categoryService.updateCategory(categoryUpdateDto);

        if(aBoolean){
            return R.success("修改分类信息成功");
        }else {
            String msg ="'分类名'已存在";
            return R.error(msg);
        }

    }


    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping()
    public R deleteCategory(@RequestParam String id){
        if(StringUtils.isEmpty(id)){
            String msg ="id不能为空";
            return R.error(msg);
        }

        Boolean aBoolean = categoryService.deleteCategory(id);
        if(aBoolean){
            String msg ="删除成功";
            return R.success(msg);
        }
        String msg ="当前分类下关联了套餐，不能删除";
        return R.error(msg);
    }

    /**
     * 获取所有
     * @return
     */
    @GetMapping("/list")
    public R getCategoryAll(@RequestParam Integer type){

        List<CategoryAllVo> categoryAll = categoryService.getCategoryAll(type);

        if(categoryAll==null){
            return R.error("列表不存在");
        }
        return R.success(categoryAll);
    }



    @GetMapping("/page")
    public R getCategoryAllPage(@RequestParam Integer page,
                                @RequestParam Integer pageSize
                                ){

        CategoryAllPageVo categoryAllPage = categoryService.getCategoryAllPage(page, pageSize);


        return R.success(categoryAllPage);
    }
}
